import os
from PIL import Image

def rename_images_in_subfolders(parent_folder_path):
    image_extensions = ['.jpg', '.jpeg', '.png']
    
    for folder_name in os.listdir(parent_folder_path):
        folder_path = os.path.join(parent_folder_path, folder_name)
        # 检查是否为子文件夹
        if os.path.isdir(folder_path):
            for i, filename in enumerate(sorted(os.listdir(folder_path))):
                # 检查文件类型是否为图片
                file_extension = os.path.splitext(filename)[1].lower()
                if file_extension in image_extensions:
                    try:
                        # 尝试打开图片文件
                        img = Image.open(os.path.join(folder_path, filename))
                        img.close()
                        # 构造新的文件名
                        new_filename = '{}_{:09d}{}'.format(folder_name, i+1, file_extension)
                        # 重命名文件
                        os.rename(os.path.join(folder_path, filename), os.path.join(folder_path, new_filename))
                    except Exception as e:
                        print(f"无法处理文件 {filename}: {e}")
                        os.remove(os.path.join(folder_path, filename))

parent_folder_path = r'validation_ori_20240622'
rename_images_in_subfolders(parent_folder_path)
print(r"图片名字更换完毕！！！")
